﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using NLog;
using ShenNius.Repository;
using ShenNius.Sys.API.Domain.Entity;
using ShenNius.Sys.API.Domain.ValueObjects.Enums;
using ShenNius.Sys.API.Dtos.Input;
using ShenNius.Sys.API.Dtos.Output;
using ShenNius.Sys.API.Infrastructure.Common;
using ShenNius.Sys.API.Infrastructure.Configs;
using ShenNius.Sys.API.Infrastructure.Extension;
using System.Threading.Tasks;

namespace ShenNius.Sys.API.Domain.Service
{
    public class LoginDomainService
    {
        private readonly IBaseRepository<User> _userRepository;
        private readonly IMapper _mapper;
        public LoginDomainService(IBaseRepository<User> userRepository, IMapper mapper)
        {
            _userRepository = userRepository;
            _mapper = mapper;
        }
        public async Task<ApiResult<LoginOutput>> LoginAsync(LoginInput loginInput)
        {
            loginInput.Password = Md5Crypt.Encrypt(loginInput.Password);
            var loginModel = await _userRepository.GetModelAsync(d => d.Name.Equals(loginInput.LoginName) && d.Password.Equals(loginInput.Password));
            if (loginModel?.Id == 0)
            {
                new LogHelper().Process(loginModel?.Name, LogEnum.Login.GetEnumText(), $"{loginModel?.Name}登陆失败，用户名或密码错误！", LogLevel.Info);
                return new ApiResult<LoginOutput>("用户名或密码错误", 500);
            }
            if (!loginInput.ConfirmLogin)
            {
                if (loginModel.IsLogin)
                {
                    return new ApiResult<LoginOutput>($"该用户【{loginInput.LoginName}】已经登录，此时强行登录，其他地方会被挤下线！", 200);
                }
            }
            loginModel.ModifyIpAddress();
            loginModel.ModifyIsLogin();
            await _userRepository.UpdateAsync(loginModel);
            var data = _mapper.Map<LoginOutput>(loginModel);
            return new ApiResult<LoginOutput>(data);
        }
    }
}
